package JavaSE.CODE.javaCollection;

public class Person implements Comparable<Person> {

    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    //重写hashcode保证name，age相同的元素，hashcode一定相同
    //如果不重写，即使字段一样，hashcode也不一样
    @Override
    public int hashCode() {
        int n1 = age;//age是int基本类型的，存在栈中，哪来的hashcode
        int n2 = name.hashCode();
        return n1+n2;
    }
    //重写equals，保证相同内容的对象加不进来
    @Override
    public boolean equals(Object o) {
        if(o==null)
            return false;
        if(o==this)
            return true;
        if(o instanceof Person){
            Person person = (Person) o;
            if(person.name==name&&person.age==age){
                return true;
            }
        }
        return false;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Person person) {
        int n1 = this.getName().compareTo(person.getName());
        int n2 = this.getAge()- person.getAge();
        return n1 == 0 ? n2 : n1;
        //先按姓名比，再按年龄比
    }
//    注1：comparable接口在继承的时候传入Person泛型，就不用强转了
//    注2：String自带compareTo方法，返回字典序差值
//    注3：int不带compareTo方法，返回差值即可
}
